package com.nav.tictactoe;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.HashMap;

import android.widget.RadioButton;

public class ServerLister implements Runnable {
	HostActivity act;
	HashMap<Integer, String> servers;
	boolean stop;
	public ServerLister(HostActivity act) {
		this.act = act;
	}
	public void stop() {
		this.stop = true;
	}
	public void run() {
		try {
			stop = false;
			while(!stop) {
				DatagramSocket socket = new DatagramSocket(Configuration.BROADCAST_PORT);
				byte[] buf = new byte[1024];
				DatagramPacket packet = new DatagramPacket(buf, buf.length);
				socket.receive(packet);
				String data = new String(buf);
				String[] toks = data.split(",");
				if(toks.length != 3) {
					System.err.println("Incorrect broadcast format received --> " + data);
					continue;
				}
				try {
					Integer.parseInt(toks[2]);
				} catch(Exception e) {
					System.err.println("Incorrect broadcast format received --> " + data);
					continue;
				}
				if(servers.values().contains(data))
					continue;
				RadioButton host = new RadioButton(act);
				host.setText(toks[0]);
				servers.put(host.getId(), data);
				act.hosts.addView(host);
			}
		} catch(Exception e) {
			// TODO show error if this happens few times
		}
	}
	public String getServer(int id) {
		return servers.get(id);
	}
}
